package com.news.servlet.admin;

import com.news.service.NewsService;
import com.news.service.impl.NewsServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/admin/categoryDelete")
public class CategoryDeleteServlet extends HttpServlet {
    private NewsService newsService = new NewsServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            // 获取分类ID
            int categoryId = Integer.parseInt(request.getParameter("id"));
            
            // 检查是否是默认分类（ID <= 8）
            if (categoryId <= 8) {
                request.getSession().setAttribute("message", "不能删除默认分类！");
                response.sendRedirect(request.getContextPath() + "/admin/categoryManage");
                return;
            }
            
            // 检查分类下是否有新闻
            int newsCount = newsService.getNewsBySortId(categoryId);
            if (newsCount > 0) {
                request.getSession().setAttribute("message", 
                    "该分类下还有" + newsCount + "条新闻，不能删除！");
                response.sendRedirect(request.getContextPath() + "/admin/categoryManage");
                return;
            }
            
            // 删除分类
            if (newsService.deleteSort(categoryId)) {
                request.getSession().setAttribute("message", "分类删除成功！");
            } else {
                request.getSession().setAttribute("message", "分类删除失败！");
            }
        } catch (Exception e) {
            request.getSession().setAttribute("message", "分类删除失败：" + e.getMessage());
        }
        
        // 重定向回分类管理页面
        response.sendRedirect(request.getContextPath() + "/admin/categoryManage");
    }
} 